package yto.freemarker.springcloud.controller;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import yto.freemarker.springcloud.entity.SecurityUser;

import java.util.Collection;

/**
 * @author dongxing
 * @create 2018-02-27 22:16
 **/
@RestController
@Slf4j
@AllArgsConstructor(onConstructor = @_(@Autowired))
public class UserController {

    @GetMapping("/{id}")
    public SecurityUser findById(@PathVariable Long id) {
        //获取登录的用户的信息
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                //打印当前登录的用户信息
                log.info("当前登录的用户为{},角色为{}", userDetails.getUsername(), authority.getAuthority());
                System.out.println("当前登录的用户为"+userDetails.getUsername()+",角色为"+authority.getAuthority());
            }
        } else {
            //do other  thing
        }
        SecurityUser build = SecurityUser.builder().username("咋忙啥").id(id).build();
        return build;

    }

}
